//
//  SYComposeView.swift
//  SYWeibo
//
//  Created by Eric on 16/7/28.
//  Copyright © 2016年 Eric. All rights reserved.
//   https://git.oschina.net/it_faner/SHVVeibo.git

import UIKit
import pop

class SYComposeView: UIView {
    
    //代表记录mainVc
    var target: UIViewController?
    
    // 保存compose 数组
    lazy var composeButtonInfos: [SYComposeButtonInfo] =  [SYComposeButtonInfo]()

    //保存按钮数组
    lazy  var buttons:[SYComposeButton] = [SYComposeButton]()
    
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: 0, width: SCREENW, height: SCREENH))
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //添加composeView
    func composeViewShow(target: UIViewController){
      //赋值
        self.target = target
        //添加view
        target.view.addSubview(self)
        
      setupButtonsAnim(true)
        
    }
    
    
    //MARK :  - 设置视图
    private func setupUI(){
        
        //添加控件
        addSubview(bgImageVeiw)
        addSubview(logoImageView)
        addChildButtons()
        bgImageVeiw .snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
            
        }
        logoImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
            
        }
       
    }
    
    //MARK :  -监听方法
    func buttonClick(button: SYComposeButton){
        //设置动画
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            //遍历保存按钮组数
            for value in self.buttons{
                //透明度
                value.alpha = 0.2
                
            //判断遍历到的按钮是否是当前点击的按钮
                if value == button {

                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else{
                
                value.transform  = CGAffineTransformMakeScale(0.2, 0.2)
                }
            }
            
            }) { (_) -> Void in
                
               UIView.animateWithDuration(0.25, animations: { () -> Void in
                for value in self.buttons{
                    //透明度
                    value.alpha = 1
                    //还原
                    value.transform = CGAffineTransformIdentity
                }
                
                }, completion: { (_) -> Void in
                    
                    guard let vcName = button.composeButtonInfo?.nextvc  else{
                        return
                    }
                    
                    guard let pn = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as? String else{
                        return
                    }
                    // 判断class 是否为nil 而且是否可以转成UIViewController.Type
                    // 为什么 “SHComposeViewController” 因为OC中根本没有命名空间 而Swift中有命名空间
                    // 如果Swift中获取自定义类的class [项目名.类名]
                    guard let cn = NSClassFromString("\(pn).\(vcName)") as? UIViewController.Type else {
                        return
                    }
                    
                    //初始化
                    let tempVc = cn.init()
                    let navC = UINavigationController(rootViewController: tempVc)
                    
                    self.target?.presentViewController(navC, animated: true, completion: { () -> Void in
                        self.removeFromSuperview()
                        
                    })
                    
                   
                    
               })
        }
        
        
        
    }
    
    //创建子控件的button
    func addChildButtons(){
        
        composeButtonInfos = getComposeButtonInfos()
        //按钮的宽和高
        let childW: CGFloat = 80
        let childH: CGFloat = 110
        //按钮的间距
        let childMargin: CGFloat = (SCREENW - childW*3)/4
        
        //循环遍历button
        for  (i,value)  in composeButtonInfos.enumerate(){
            
            //得到行数和列数
            let col = CGFloat(i%3)
            let row = CGFloat(i/3)
            //创建button
            let button = SYComposeButton()
            //button的属性赋值
            button.composeButtonInfo = value
            
            //点击事件
            button.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            button.setImage(UIImage(named: value.icon ?? ""), forState: UIControlState.Normal)
            button.setTitle(value.title, forState: UIControlState.Normal)
            button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
            button.frame = CGRect(x: childMargin + (childW+childMargin)*col, y: (childH+childMargin)*row + SCREENH, width: childW, height: childH)

            addSubview(button)
            //保存按钮
            buttons.append(button)
        }
        
    }
    
    // 读取plist文件 得到数据
    func getComposeButtonInfos()->[SYComposeButtonInfo]{
        //获取路径
        let file = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)
        //plist 文件转成  swift 中是不能用装NSArray的   只能用OC中的转
        let arry = NSArray(contentsOfFile: file!)
        //创建一个临时数组
        var tempArray: [SYComposeButtonInfo] =  [SYComposeButtonInfo]()
        //遍历字典转模型
        for dic in arry!{
            //创建模型
            let composeButtonInfo = SYComposeButtonInfo(dict: dic as! [String: AnyObject])
            //添加模型
        tempArray.append(composeButtonInfo)
        
        }
        return tempArray
        
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        setupButtonsAnim(false)
        // 延迟删除当前view
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.removeFromSuperview()
        }

        
    }
    // 设置buttons动画 (isUp==true 代表向上 显示按钮  false 代表 消失按钮)
    func setupButtonsAnim(isUp: Bool){
        // 距离
        let margin: CGFloat = isUp ? -350 : 350
    
        let set = isUp ? buttons.enumerate() : buttons.reverse().enumerate()
        
        //遍历按钮数组 分别设置动画
        for (i,value) in set{
            //设置动画
            let anim = POPSpringAnimation(propertyNamed:kPOPViewCenter)
            //设置toValue
            anim.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y + margin))
            //开始时间
            anim.beginTime = CACurrentMediaTime() + Double(i)*0.025
            //弹性系数
            anim.springBounciness = 10
            //动画速度
            anim.springSpeed = 8
            
            value.pop_addAnimation(anim, forKey: nil)
        }
    
    }
    
//MARK :  -懒加载控件
    //磨砂图片
    private lazy var bgImageVeiw: UIImageView = UIImageView(image:  UIImage.getScreenShot().applyLightEffect())

    private lazy var logoImageView: UIImageView = UIImageView(imgName: "compose_slogan")
    
}












